<!--
/**
* Copyright (C) 2022-2023 Timber Chain Cloud (TimberCLD). All Rights Reserved.
* 
* @author: luoweijian
* @email: 807301075@qq..com
* @site: https://www.timbercld.com/
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
*  limitations under the License.
*/
-->
<template>
  <div class="tccui-wrapper tccui-page__login">
    <div class="tccui-content__wrapper">
      <main class="tccui-content">
        <div class="login-body">
          <div class="login-header">
            <div class="logo-svg">
              <img src="@/assets/img/logo.svg" />
            </div>
            <h2 class="login-brand">{{ t('brand.lg') }}</h2>
          </div>
          <el-form :model="formData" :rules="formRules" ref="formRef" @keyup.enter="submitDataFormHandle()" status-icon>
            <el-form-item>
              <el-select v-model="$i18n.locale" class="w-percent-100">
                <el-option v-for="(val, key) in i18nMessages" :key="key" :label="val._lang" :value="key"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="username">
              <el-input v-model="formData.username" :placeholder="t('login.username')">
                <template #prefix>
                  <span class="el-input__icon">
                    <el-icon>
                      <User />
                    </el-icon>
                  </span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="formData.password" type="password" :placeholder="t('login.password')">
                <template #prefix>
                  <span class="el-input__icon">
                    <el-icon>
                      <Lock />
                    </el-icon>
                  </span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="captcha">
              <el-row :gutter="20" style="width: 100%">
                <el-col :span="14">
                  <el-input v-model="formData.captcha" :placeholder="t('login.captcha')">
                    <template #prefix>
                      <span class="el-input__icon">
                        <el-icon>
                          <Lock />
                        </el-icon>
                      </span>
                    </template>
                  </el-input>
                </el-col>
                <el-col :span="10" class="login-captcha">
                  <img :src="captchaPath" @click="getCaptcha()" />
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitDataFormHandle" :loading="loginLoading.value" class="w-percent-100">
                {{ t('login.title') }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="login-footer">
          <p>2022-2023 © timbercld.com</p>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import Cookies from 'js-cookie';
import { getUUID } from '@/utils';
import { useI18n } from 'vue-i18n';
import { messages } from '@/i18n';
import { useRouter } from 'vue-router';
import type { ElForm } from 'element-plus';
import { globalApi } from '@/api/global';
import debounce from 'lodash/debounce';
import { ElMessage, FormRules } from 'element-plus';
import baseApi from '@/config';
// #region 类型
interface FormValue {
  username: string;
  password: string;
  uuid: string;
  captcha: string;
}
// #endregion

// #region 属性
const { t } = useI18n();
const router = useRouter();
const captchaPath = ref('');

const i18nMessages = ref(messages);
const loginLoading: any = ref(false);

const formRef = ref<InstanceType<typeof ElForm>>();

const formData = reactive<FormValue>({
  username: '',
  password: '',
  uuid: '',
  captcha: '',
});

const formRules = reactive<FormRules<FormValue>>({
  username: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
  password: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
  captcha: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
});
// #endregion

// #region 方法

// 获取验证码
const getCaptcha = () => {
  formData.uuid = getUUID();
  captchaPath.value = `${baseApi}/timbercld/captcha?uuid=${formData.uuid}`;
};
// 登录逻辑
function login() {
  loginLoading.value = true;
  formRef.value?.validate(async (valid) => {
    if (valid) {
      const res = await globalApi.login(formData);
      loginLoading.value = false;
      if (res.code === 0) {
        Cookies.set('token', res.data!.token);
        ElMessage({
          message: t('login.loginSuccText'),
          type: 'success',
          duration: 1000,
        });
        router.push({ name: 'dashboard' });
      } else {
        getCaptcha();
        ElMessage.error(res.msg);
      }
    }
  });
}
// 防抖提交
const submitDataFormHandle = debounce(login, 1000, { leading: true, trailing: false });
// #endregion
getCaptcha();
</script>
